<?php

namespace App\Console\Commands;

use App\Helper;
use App\Lib\Sdk\Manager;
use App\Models\Circle;
use App\Models\Group;
use App\Models\GroupConfig;
use App\Models\Queue;
use App\Models\Robots;
use App\Models\Send;
use App\Models\System;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use PHPUnit\TextUI\Help;

class Sendmsg extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '发送消息队列';

    /** @var \App\Lib\Sdk\Robot\IRobot $sdk*/
    protected $sdk;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->sdk = Manager::getSdk();
    }

    /**
     * Execute the console command.
     * 每分钟运行
     * @return mixed
     */
    /*public function handle()
    {
        $isStart = true;
        $lastId = 1;
        $users = [];
        $robot = null;
        while ($isStart  || !empty($users->toArray())) {
            $isStart = false;
            $users = User::orderBy('id', 'asc')
                ->where("id", ">", 1)
                ->where("id", ">", $lastId)
                ->limit(20)
                ->get();
            if (empty($users)) return 0;
            foreach ($users as $user) {
                echo "处理".$user->id."中\n";
                $robot = Robots::where("user_id", $user->id)->first();
                $this->send($user->id, $robot);
                $lastId = $user->id;
            }
        }
    }*/

    protected function getUser($uid)
    {
        return User::where("id", ">", $uid)->first();
    }


    public function handle()
    {

        //间隔 (分)
        $config = System::getConfig();
        $interval = $config['robot_interval'];
        $key = "__INTERVAL__";
        $last = Cache::get($key);
        $dnow = date("YmdHi");
        if ((int)$last + $interval > $dnow) {
            return false;
        }
        Cache::put($key, $dnow);
        $queue = Queue::query()->orderBy('id', 'asc')
                ->where("is_read", 0)
                ->where("type", Queue::send_type_group)
                ->limit(1)
                ->first();
        if ($queue) {
            $this->start($queue);
        }
        $queue = Queue::query()->orderBy('id', 'asc')
            ->where("is_read", 0)
            ->where("type", Queue::send_type_circle)
            ->limit(1)
            ->first();
        if ($queue) {
            $this->start($queue);
        }
    }


    protected function start($queue) {
        $lastId = 1;
        while (true) {
            echo "lastId:" . $lastId;
            $user = $this->getUser($lastId);
            if (is_null($user)) {
                break;
            }
            echo  "正在操作用户". $user->id. "\n";
            $robot = Robots::where("user_id", $user->id)->first();
            try {
                $this->send($queue, $robot);
            } catch (\Exception $e) {
                Log::error($e->getFile());
                Log::error($e->getLine());
                Log::error($e->getMessage());
            }
            $lastId = $user->id;
        }
        $queue->update(['is_read' => 1]);
        return false;
    }

    //发送条件
    protected function check($uid, $robot)
    {
        $sendConfig = GroupConfig::getConfig($uid);
        if ($sendConfig->is_open == 0) {
            echo "用户已关闭发送\n";
            return false;
        }
        list($h,$i,$s) = explode(":", $sendConfig->start_time);
        $startTime = $h.$i;
        list($h,$i,$s) =  explode(":",$sendConfig->end_time);
        $endTime = $h.$i;
        $now = date("Hi");
        if ((int)$now < (int)$startTime || (int)$now > (int)$endTime){
            echo "不在发送时间段:" . $sendConfig->start_time . "-" . $sendConfig->end_time . ",当前时间".$now."\n" ;
            return false;
        };
       return true;
    }


    protected function message(Queue $queue, Robots $robot)
    {
        $res = false;
        switch ($queue->type) {
            case Queue::send_type_group:
                echo "发送群组\n";
                $groups = Group::getByUid($robot->user_id);
                if (is_null($groups)) {
                    echo "用户" . $robot->user_id  . "没有群组\n";
                }
                $ids = array_keys($groups);
                $send = Send::where("id", $queue->message_id)->first();
                if (!$send) {
                    echo  "没有找到信息\n";
                    return false;
                };
                $images = $send->images;
                $images = json_decode($images, true);
                if (json_last_error() == 0) {
                    foreach ($images as $image) {
                        if (is_array($image) && isset($image['url'])) {
                            $image = $image['url'];
                        }
                        $res = $this->sdk->sendImgMessage($ids, Helper::imgToBase64($image), $robot);
                    }
                }
                $res = $this->sdk->send($robot, Helper::convertCouponLinkOfSend($send, $robot->user_id), $ids);
                $send->send_time = date("Y-m-d H:i:s",time());
                $send->status = 1;
                $send->save();
                break;
            case Queue::send_type_circle:
                echo "发送朋友圈\n";
                $send = Circle::where("id", $queue->message_id)->first();
                $res = $this->sdk->sendFriendsCircle($robot, $send);
                $send->send_time = date("Y-m-d H:i:s",time());
                $send->status = 1;
                $send->save();
                break;
        }
        echo ("发送结果:" . (int)$res . "\n");
        return $res;
    }

    protected function send($queue, Robots $robot)
    {
         $res = $this->check($robot->user_id, $robot);
         if ($res) {
             echo "准备发送\n";
         } else {
             echo "不予发送\n";
             return 0;
         }
         $this->message($queue, $robot);
    }
}
